// pages/shop/shop.js
import Api from '../../utils/http/api'
import common_utils from '../../utils/common_utils'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    categoryList: [], //左边商品分类 数据源
    productsList: [], //右边商品列表 数据源
    pageNum: 1,
    pageSize: 10,
    hasLoadMore: false, //是否加载更多
    activeKey: '', //左侧当前选中的tab
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getCategory()
  },
  // 加载更多
  fecthMore() {
    if (this.data.hasLoadMore) {
      this.getProducts()
    }
  },
  //点击左侧tab 切换数据
  onTabClick(e) {
    console.log(e)
    let activeKey = e.detail.activeKey
    this.setData({
      activeKey,
      hasLoadMore: false,
      productsList: [],
      pageNum: 1,
    })

    this.getProducts()
  },
  //商品item 点击
  onProduct(e) {
    let obj = e.currentTarget.dataset.item
    wx.navigateTo({
      url: '/package_shop/pages/product/product?id=' + obj.id,
    })
  },

  // 获取右侧商品列表
  getProducts() {
    this.setData({
      hasLoadMore: false
    })
    let params = {
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize,
      category: this.data.activeKey
    }
    Api.getProducts(params).then(res => {
      let list = res.data
      list.forEach((item) => {
        if (item.picture) {
          item.picture = common_utils.getApiImg(item.picture)
        }
      })

      this.setData({
        productsList: this.data.productsList.concat(list),
        pageNum: list.length >= this.data.pageSize ? this.data.pageNum + 1 : this.data.pageNum,
        hasLoadMore: list.length >= this.data.pageSize
      })
    }).catch(err => console.log(err))
  },
  // 获取 左侧 商品分类
  getCategory() {
    let params = {

    }
    Api.getCategory(params).then(res => {
      let list = res.data
      list.forEach((item) => {
        if (item.picture) {
          item.picture = common_utils.getApiImg(item.picture)
        }
      })
      this.setData({
        categoryList: list,
        activeKey: list[0].code
      })
      ///第一次加载分类列表的时候，加载商品列表数据
      this.getProducts()
    }).catch(err => console.log(err))
  },
})